package com.kizuki.io;

import org.junit.Test;

import java.nio.Buffer;
import java.nio.ByteBuffer;

public class TestBuffer {

    @Test
    public void test(){
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        printBufferInfo("init", buffer);

        buffer.put("Im happy".getBytes());
        printBufferInfo("afterAdd", buffer);

        /**
         * 切换成读模式
         * limit变成了position的位置了
         * 而position变成了0
         */
        buffer.flip();
        printBufferInfo("afterFilp", buffer);

        byte[] bytes = new byte[buffer.limit()];
        buffer.get(bytes);
        System.out.println(new String(bytes));
        printBufferInfo("afterGet", buffer);

        buffer.clear();
        printBufferInfo("afterClear", buffer);

        /**
         * buffer.clear() 不是真正的删除数据，只是修改那四个参数
         * afterClear value = Im happy
         */
        System.out.println("afterClear value = " + new String(buffer.array()));
    }

    public static void printBufferInfo(String preStr, Buffer buffer) {
        System.out.println(preStr + " capacity = " + buffer.capacity());
        System.out.println(preStr + " limit = " + buffer.limit());
        System.out.println(preStr + " position = " + buffer.position());
        System.out.println(preStr + " mark = " + buffer.mark());
        System.out.println();
    }


}
